//
//  CCViewModel.m
//  test02
//
//  Created by lzh on 2020/11/24.
//  Copyright © 2020 NO. All rights reserved.
//

#import "CCViewModel.h"
#import "ArtBannerList.h"
#import <objc/runtime.h>
#import "UITableView+JYTableLayoutCell.h"
@interface CCViewModel()

@property(nonatomic,weak)id cellDelegate;
@property(nonatomic,strong)UITableView * tableView;
@property(nonatomic,strong)NSMutableArray * allContents;
// cell 的配置信息
@property (nonatomic, strong) NSMutableDictionary<NSString * ,JYBaseNode *> *nodeCache;

// 设置 edgeInsets 时 标记 每组最后一个 下方偏移是否清0
@property (nonatomic, assign) BOOL ridLastBottomMargin;

@property (nonatomic, assign) EJYCellSeparatorType separatorType;


@end

@implementation CCViewModel

- (instancetype)init {
    if (self = [super init]) {
        self.nodeCache = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)registCellNodes:(NSArray<JYBaseNode *> *)nodes byTableView:(UITableView *)tableView cellDelegate:(id)cellDelegate{
  
    _cellDelegate = cellDelegate;
    _tableView = tableView;
//    self.isMoreCell = NO;
    [nodes enumerateObjectsUsingBlock:^(JYBaseNode * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([obj isKindOfClass:[JYNode class]]) {
            [self registNode:(JYNode *)obj byTableView:tableView];
        }
//        else if ([obj isKindOfClass:[JYGroupNode class]]) {
//            [self registGroupNode:(JYGroupNode *)obj byTableView:tableView];
//        }
    }];
    
    // 取消系统分割线
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
}
- (void)registNode:(JYNode *)node byTableView:(UITableView *)tableView {
    
    if (node.groupCellNode.count >1) {
//        self.isMoreCell = YES;
    }
    [node.groupCellNode enumerateObjectsUsingBlock:^(JYCellNode* cellNode, NSUInteger idx, BOOL * _Nonnull stop) {
        [self registCellNode:cellNode byTableView:tableView];
    }];
    [self.nodeCache setObject:node forKey:node.identifier];
}
- (void)registCellNode:(JYCellNode *)cellNode byTableView:(UITableView *)tableView {

    if (cellNode.nib != nil) {
        [tableView registerNib:cellNode.nib forCellReuseIdentifier:[cellNode cellIdentifier]];
    }else {
        [tableView registerClass:cellNode.cellClass forCellReuseIdentifier:[cellNode cellIdentifier]];
    }
}
#pragma mark - Table View 辅助计算
- (NSInteger)numberOfSections{
    return self.allContents.count;
}
// 因为存在 多cell拼接 所以要做偏移计算
- (NSInteger)numberOfRowsInSection:(NSInteger)section{
    return [self caculateCountInSection:section];
}
- (CGFloat)heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self heightForRowAtIndexPath:indexPath config:nil];
}
- (NSInteger)caculateCountInSection:(NSInteger)section
{
    NSArray* contents = [self.allContents objectAtIndex:section];

    return contents.count;
}
- (CGFloat)heightForRowAtIndexPath:(NSIndexPath *)indexPath config:(void (^)(UITableViewCell *aCell,__kindof JYBaseNode* aNode))aConfig{
    
    CGFloat height = 0.;
    JYBaseNode *node = [self getCellNodeAtIndexPath:indexPath];
    JYCellNode *cellNode = node.currentCellNode;
    if (cellNode.cellHeight > 0) {
           height = cellNode.cellHeight;
       }else if (class_getClassMethod(node.currentCellNode.cellClass, @selector(heightForContent:)) != nil){
           height = [node.currentCellNode.cellClass heightForContent:node.content];
       }else if (class_getClassMethod(node.currentCellNode.cellClass, @selector(heightForContent:cellNode:)) != nil){
           height = [node.currentCellNode.cellClass heightForContent:node.content cellNode:node.currentCellNode];
       }else{
           if (self.tableView.frame.size.width == 0) { // 没宽度无法算高度
             CGRect frame = self.tableView.frame;
             frame.size.width = [UIScreen mainScreen].bounds.size.width;
             self.tableView.frame = frame;
           }
           NSString *key = [node heightCacheKey];
          height = [self.tableView jy_heightForCellClass:cellNode.cellClass withIdentifier:[cellNode cellIdentifier] cacheContent:node.content key:key configuration:^(id cell) {
            [self configCell:cell forNode:node AtIndexPath:indexPath config:aConfig];
            if (aConfig) {
                aConfig(cell,node);
            }
          }];
       }
       
       UIEdgeInsets edgeInset = cellNode.edgeInsets;
       height += edgeInset.top;
       if (self.ridLastBottomMargin && indexPath.row != [self numberOfRowsInSection:indexPath.section] - 1) {
           height += edgeInset.bottom;
       }
       return height;
}

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self cellForRowAtIndexPath:indexPath config:nil];
}
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath config:(void (^)(UITableViewCell *aCell,__kindof JYBaseNode* aNode))aConfig{
    
    JYBaseNode *node = [self getCellNodeAtIndexPath:indexPath];
    if (node == nil) { // 如果是空 表示可能越界了 防止崩溃
        NSAssert(node != nil, @"请检查可能越界了");
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        cell.hidden = YES;
        return cell;
    }
    NSString *identifier = [node.currentCellNode cellIdentifier];
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    [self configCell:cell forNode:node AtIndexPath:indexPath config:aConfig];
    return cell;
}

- (void)configCell:(UITableViewCell *)cell forNode:(JYBaseNode *)node AtIndexPath:(NSIndexPath *)indexPath config:(void (^)(UITableViewCell *aCell,JYBaseNode* aNode))aConfig{
  
    // 边距 分割线 以及颜色设置
    JYCellNode *cellNode = node.currentCellNode;
    if (!UIEdgeInsetsEqualToEdgeInsets(cellNode.edgeInsets, UIEdgeInsetsZero)) {
        UIEdgeInsets edge = cellNode.edgeInsets;
        if (self.ridLastBottomMargin && indexPath.row == [self numberOfRowsInSection:indexPath.section] - 1) {
            edge.bottom = 0;
        }
        cell.edgeInsets = edge;
    }else {
        cell.edgeInsets = UIEdgeInsetsZero;
    }
    cell.jy_indexPath = indexPath;
    [cell configEdgeInsetsColor:cellNode.marginColor];
    [cell configTopColor:cellNode.topColor leftColor:cellNode.leftColor bottomColor:cellNode.bottomColor rightColor:cellNode.rightColor];
    if (!cell.jy_hiddenLine) {
        switch (self.separatorType) {
            case EJYCellSeparatorTypeNone:
            {
            }
                break;
                
            case EJYCellSeparatorTypeSeparator:
            {
                [cell configSeparatorColor:cellNode.lineColor hidden:NO edgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
            }
                break;
                
            case EJYCellSeparatorTypeHiddenLast:
            {
                BOOL hidden = indexPath.row == [self numberOfRowsInSection:indexPath.section] - 1;
                [cell configSeparatorColor:cellNode.lineColor hidden:hidden edgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
            }
                break;
                
            case EJYCellSeparatorTypeCustom:
            {
                //
                BOOL isFirst = indexPath.row == 0;
                BOOL isLast = indexPath.row == [self numberOfRowsInSection:indexPath.section] - 1;
                if (isFirst) {
                    [cell configTopSeparatorColor:cellNode.lineColor hidden:NO edgeInsets:UIEdgeInsetsZero];
                }else if (isLast) {
                    [cell configSeparatorColor:cellNode.lineColor hidden:NO];
                }else {
                    [cell configTopSeparatorColor:cellNode.lineColor hidden:YES edgeInsets:UIEdgeInsetsZero];
                    [cell configSeparatorColor:cellNode.lineColor hidden:NO edgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
                }
            }
                break;
                
            default:
                break;
        }
    }
    
    //  内容设置
    if ([cell respondsToSelector:@selector(setCellContent:)]) {
        [(id)cell setCellContent:node.content];
    }else if ([cell respondsToSelector:@selector(setCellContent:metaContent:cellNode:)]) {
        [(id)cell setCellContent:node.content metaContent:node.metaContent cellNode:node.currentCellNode];
    }
  
    if ([cell respondsToSelector:@selector(setCellDelegate:)]) {
      [(id)cell setCellDelegate:self.cellDelegate];
    }
  
    if (aConfig) {
      aConfig(cell,node);
    }
}

- (JYBaseNode *)getCellNodeAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *contents = [self contentsAtInSection:indexPath.section];
    if (contents.count <= indexPath.row) {
        return nil;
    }
    id content = contents[indexPath.row];
    JYNode *node = (JYNode *)self.nodeCache[[JYNode identifierForContent:content]];
    NSAssert([node isKindOfClass:[JYNode class]], @"只有JYNode 才有这种情况");
    [node recordCurrentIndexPath:indexPath currentIndex:0 metaContent:content];
    return node;

}
#pragma mark - 懒加载
- (NSMutableArray<NSMutableArray *> *)allContents{
    if (!_allContents) {
        _allContents = [[NSMutableArray alloc] init];
    }
    return _allContents;
}
//不存在就建一个新的数组
- (NSMutableArray *)contentsAtInSection:(NSInteger)aSection
{
    NSMutableArray* contents = nil;
    if ([self.allContents count] > aSection) {
        contents = [self.allContents objectAtIndex:aSection];
    } else {
        if (self.allContents.count == aSection) {
            contents = [NSMutableArray array];
            [self.allContents addObject:contents];
        }
    }
    NSAssert(contents, @"插入的aSection超出了现有的");
    return contents;
}

-(void)addData{
    
    NSMutableArray * arr = [NSMutableArray array];
    for (int i=0; i<5; i++) {
        
        ArtBannerList * list = [[ArtBannerList alloc]init];
        
        [arr addObject:list];
    }

    [self addContents:arr atSection:0];
}

- (void)addContents:(NSArray *)aContents atSection:(NSInteger)aSection
{
    NSMutableArray* contents = [self contentsAtInSection:aSection];
    [contents addObjectsFromArray:aContents];
}
@end
